const AUTH = require('../http/api')
//检测微信用户登录状态方法
function checkWXStatus() {
  return new Promise((resolve, reject) => {
    wx.checkSession({
      success: () => {
        resolve(true)
      },
      fail: () => {
        resolve(false)
      }
    })
  })
}
//检测用户是否登录
function hasUserLoginChecked() {
  //先查看本地有没有token
  const token = wx.getStorageSync('token')
  if (!token) return false;
  //再查看本地token是否有效
  AUTH.checkTokeValidApi(token).then(res => {
    console.log(res);
    //0代表成功 非0代表token无效
    if (res.code !== 0) {
      //如果toke无效，删除本地token
      wx.removeStorageSync('token')
      return false
    }
  })

  //再查看当前用户在小程序的登录态
  const flag = checkWXStatus()
  if (!flag) {
    //如果toke无效，删除本地token
    wx.removeStorageSync('token')
    return false
  }
  return true
}
//自动注册与登录方法
function authRegAndLogin() {
  return new Promise((resolve, reject) => {

    wx.login({
      async success(res) {
        console.log('code码：', res.code)
        //调用自动注册登录接口
        const result = await AUTH.authRegAndLoginApi(res.code)
        //保存token
        wx.setStorageSync('token', result.data.token)
        //保存用户id
        wx.setStorageSync('uid', result.data.uid)
      }
    })
  })
}

function Fnicons() {
  let token = wx.getStorageSync('token')
  let cartNum;
  //通过购物车接口获取购物车商品数量
  AUTH.getCartListApi(token).then(res => {
    console.log(res);
    // 显示图标
    cartNum = res.data.number
    let num = cartNum
    wx.setStorageSync('num', num)
    if (cartNum != 0) {
      //购物车角标
      wx.setTabBarBadge({
        index: 3, //tabBar序号，从0开始计数
        text: `${num}`
      })
    } else {
      //移除角标
      wx.removeTabBarBadge({
        index: 2,
      })
    }
  })
}
Fnicons()
module.exports = {
  hasUserLoginChecked,
  authRegAndLogin,
  Fnicons
}